//mine.js
import { getMyCoin, getMobileAuth, getRule, getAdvList, userLogin } from '../../utils/api';
import Notify from '../../miniprogram_npm/vant-weapp/notify/notify';
import Toast from '../../miniprogram_npm/vant-weapp/toast/toast';
//获取应用实例
const app = getApp()

Page({
	data: {
		userInfo: {},
		hasUserInfo: false,
		canIUse: wx.canIUse('button.open-type.getUserInfo'),
		currentUser: {},
		modelList: [
			{
				id: '1',
				icon: '../../image/mineCommitIcon.png',
				name: '我评论的',
				url: '../minePages/mineComment/index'
			},{
				id: '2',
				icon: '../../image/mineLikeIcon.png',
				name: '我点赞的',
				url: '../minePages/mineLike/index'
			},
      // {
			// 	id: '3',
			// 	icon: '../../image/mineShareIcon.png',
			// 	name: '我转发的',
			// 	url: '../minePages/mineShare/index'
			// },
      		{
				id: '4',
				icon: '../../image/moneyIcon.png',
				name: '我的明细',
				url: '../minePages/moneyDetails/index'
			},{
				id: '5',
				icon: '../../image/aboutUsIcon.png',
				name: '关于我们',
				url: '../minePages/aboutUs/index'
			}
		],
		advObj: null,
		inforModal: false,
		ruleMsg: ''
	},
	// 进入页面判断用户是否授权
	toGetUserInfor() {
		const userInfo = wx.getStorageSync('userInfo')
		const userId = wx.getStorageSync('userId')
		if (userInfo && userId) {
			app.globalData.userInfo = userInfo;
			app.globalData.uid = userId;
		}else{
			// 获取用户信息
			wx.getSetting({
				success: res => {
					if (res.authSetting['scope.userInfo']) {
						// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
						wx.getUserInfo({
							success: res => {
								// 可以将 res 发送给后台解码出 unionId
								app.globalData.userInfo = res.userInfo
								wx.setStorageSync('userInfo', res.userInfo)
								// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
								// 所以此处加入 callback 以防止这种情况
								if (app.userInfoReadyCallback) {
									app.userInfoReadyCallback(res)
								}
							},
							fail: () => {
								app.globalData.userInfo = null;
								wx.redirectTo({
									url: '/pages/login/index'
								})
							}
						})
					}
					else{
						wx.redirectTo({
							url: '/pages/login/index'
						})
					}
				}
			})
		}
	},
	// 获取手机号
	getPhoneNumber(e) {
		if(e.detail.iv) {
			wx.login({
				success: res => {
					if (res.code) {
						const params = {
							code: res.code,
							uid: app.globalData.uid,
							iv: e.detail.iv,
							encryptedData: e.detail.encryptedData
						}
						getMobileAuth(params).then(res=>{
							if(res.code === 200){
								this.toGetMyCoin();
							}else{
								this.errorToast(res.msg,'error');
							}
						}).catch(e=>{
							Toast.clear();
							this.errorToast('服务异常','error');
						})
					}
				}
			})
		}
	},
	// 获取金币信息
	toGetMyCoin() {
		const params = {
			uid: app.globalData.uid
		};
		getMyCoin(params).then((res)=>{
			wx.stopPullDownRefresh();
			if(res.code === 200){
				this.setData({
					currentUser: res
				})
			}else{
				this.errorToast(res.msg,'error');
			}
		}).catch(e=>{
			Toast.clear();
			this.errorToast('服务异常','error');
		})
	},
	// 获取规则
	toGetRule() {
		getRule().then(res=>{
			if(res.code === 200){
				this.setData({
					ruleMsg: res.ruleMsg
				})
			}else{
				this.errorToast(res.msg,'error');
			}
		}).catch(e=>{
			Toast.clear();
			this.errorToast('服务异常','error');
		})
	},
	// 展开评论
	showModal() {
		this.setData({
			inforModal: true
		}) 
	},
	// 隐藏弹窗
	hideModal() {
		this.setData({
			inforModal: false
		}) 
	},
	toItemUrl(event) {
		if(this.data.hasUserInfo){
			wx.navigateTo({
				url: event.currentTarget.dataset.url
			})
		}else{
			wx.getUserInfo({
				success: res => {
					if(res.userInfo){
						app.globalData.userInfo = res.userInfo
						wx.setStorageSync('userInfo', res.userInfo)
						this.setData({
							userInfo: res.userInfo,
							hasUserInfo: true
						})
					}else{
						app.globalData.userInfo = null;
						this.setData({
							userInfo: {},
							hasUserInfo: false
						})
					}
				}
			})
		}
	},
	// 跳转广告详情
	toAdvDetails(event) {
		const img = event.currentTarget.dataset.img;
		const url = event.currentTarget.dataset.url;
		wx.navigateTo({
			url: `../advDetails/index?img=${img}&url=${url}`
		})
	},
	// 登录
	toLogin(userInfo) {
		wx.login({
			success: res => {
				// 发送 res.code 到后台换取 openId, sessionKey, unionId
				const params = {
					code: res.code,
					userInfo: userInfo
				}
				userLogin(params).then((res)=>{
					if(res.code === 200){
						wx.setStorageSync('userId', res.uid)
						app.globalData.uid = res.uid;
						this.toGetMyCoin();
					}
				})
			}
		})
	},
	errorToast(text, type) {
		switch(type) {
			case 'success':
				Notify({
					text: text,
					color: '#ffffff',
					backgroundColor: '#008000'
				});
				break;
			case 'error':
				Notify({
					text: text,
					color: '#ffffff',
					backgroundColor: '#FF0000'
				});
				break;
			case 'warn':
				Notify({
					text: text,
					color: '#ffffff',
					backgroundColor: '#FFA500'
				});
				break;
		}
	},
	onLoad() {
		// wx.hideShareMenu();
		// this.toGetUserInfor();
    	this.toGetAdvList();
		this.setData({
			advObj: app.globalData.advObj
		})
		if(app.globalData.advObj.ad_status == 1){
			this.toGetRule();
		}
		if (app.globalData.userInfo) {
			this.setData({
				userInfo: app.globalData.userInfo,
				hasUserInfo: true
			})
			this.toLogin(app.globalData.userInfo);
		} else if (this.data.canIUse){
			// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
			// 所以此处加入 callback 以防止这种情况
			app.userInfoReadyCallback = res => {
				wx.setStorageSync('userInfo', res.userInfo)
				this.setData({
					userInfo: res.userInfo,
					hasUserInfo: true
				})
				this.toLogin(res.userInfo);
			}
		} else {
			// 在没有 open-type=getUserInfo 版本的兼容处理
			wx.getUserInfo({
				success: res => {
					app.globalData.userInfo = res.userInfo
					wx.setStorageSync('userInfo', res.userInfo)
					this.setData({
						userInfo: res.userInfo,
						hasUserInfo: true
					})
					this.toLogin(res.userInfo);
				},
				fail: () => {
					app.globalData.userInfo = null;
					this.setData({
						userInfo: {},
						hasUserInfo: false
					})
				}
			})
		}
	},
	onShow() {
		this.toGetMyCoin();
	},
	getUserInfo: function(e) {
		if(e.detail.userInfo){
			app.globalData.userInfo = e.detail.userInfo;
			wx.setStorageSync('userInfo', e.detail.userInfo);
			this.setData({
				userInfo: e.detail.userInfo,
				hasUserInfo: true
			})
			this.toLogin(e.detail.userInfo);
		}else{
			app.globalData.userInfo = null;
			this.setData({
				userInfo: {},
				hasUserInfo: false
			})
		}
	},
	// 获取广告信息
	toGetAdvList() {
		getAdvList().then((res) => {
		if (res.code === 200) {
			this.setData({
			advObj: res.data
			})
			app.globalData.advObj = res.data;
		} else {
			this.errorToast(res.msg, 'error');
		}
		}).catch(e => {
		Toast.clear();
		this.errorToast('服务异常', 'error');
		})
	},
	// 下拉刷新
	onPullDownRefresh() {
		this.toGetMyCoin();
    	this.toGetAdvList();
	}
})
